package md.NJavaBase;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.util.Log;
import android.view.WindowManager;

import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class NJavaBase {
    //public static final String EVT_RESUME = "RESUME";
    //public static final String EVT_PAUSE = "PAUSE";
    public static final String EVT_REQUEST_PERMISSIONS_RESULT = "RequestPermissionsResult";
    public static final String EVT_ACTIVITY_RESULT = "ActivityResult";



    static String Tag = "NJavaBase";

    //初始化
    public static void Go(IBaseFuncs func)
    {
        m_BaseFuncs = func;

        //初始化主循环
        MainLoop.Go();

        func.initLogic();

        //Æô¶¯¸÷ÖÖ¹ã¸æ
        class VideoCallback implements IAdLoaderCallback
        {
            //¹ã¸æ¼ÓÔØ³É¹¦
            @Override
            public void onLoad()
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showVideoAdResult({'r':9});")
                        );
                    }
                }
                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }

            //¹ã¸æ±»¹Ø±Õ
            @Override
            public void onClose(final boolean reward)
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {
                        String cmd =  String.format("AppDelegate.showVideoAdResult({'r':%d});",reward?0:1);
                        Log.d(Tag, String.format("onClose cmd:%s reward:%s",cmd,reward?"true":"false"));
                        Cocos2dxJavascriptJavaBridge.evalString(cmd);
                    }
                }

                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }

            //¼ÓÔØ´íÎó
            @Override
            public void onError(final String errCode)
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showVideoAdResult({'code':'%s','r':2});",errCode)
                        );
                    }
                }

                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }
        }
        VideoAdMgr.I().go(new VideoCallback());
        Log.d(Tag,"VideoAdMgr init end2");


        class InterstitialCallback implements IAdLoaderCallback
        {
            //¹ã¸æ¼ÓÔØ³É¹¦
            @Override
            public void onLoad()
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showInterstitialAdResult({'r':9});")
                        );
                    }
                }
                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }

            //¹ã¸æ±»¹Ø±Õ
            @Override
            public void onClose(final boolean reward)
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showInterstitialAdResult({'r':%d});",reward?0:1)
                        );
                    }
                }

                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }

            //¼ÓÔØ´íÎó
            @Override
            public void onError(final String errCode)
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showInterstitialAdResult({'code':'%s','r':2});",errCode)
                        );
                    }
                }

                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }



        }
        InterstitialAdMgr.I().go(new InterstitialCallback());
        Log.d(Tag,"InterstitialAdMgr init end");

        class SplashAdCallback implements IAdLoaderCallback
        {
            //¹ã¸æ¼ÓÔØ³É¹¦
            @Override
            public void onLoad()
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {

                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showSplashAdResult({'r':9});")
                        );
                    }
                }
                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }

            //¹ã¸æ±»¹Ø±Õ
            @Override
            public void onClose(final boolean reward)
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {

                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showSplashAdResult({'r':%d});",reward?0:1)
                        );
                    }
                }

                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }

            //¼ÓÔØ´íÎó
            @Override
            public void onError(final String errCode)
            {
                class MRunnable implements Runnable
                {
                    @Override
                    public void run() {

                        Cocos2dxJavascriptJavaBridge.evalString(
                                String.format("AppDelegate.showSplashAdResult({'code':'%s','r':2});",errCode)
                        );
                    }
                }

                Cocos2dxHelper.runOnGLThread(new MRunnable());
            }



        }
        SplashAdMgr.I().go(new SplashAdCallback());
        Log.d(Tag,"SplashAdMgr init end");
    }

    public static void setAdConsent(boolean v)
    {
        m_BaseFuncs.setAdConsent(v);
    }

    public static void logOut(String tag,String msg)
    {
        m_BaseFuncs.logOut(tag,msg);
    }

    //添加一个行为重写
    public static void addActivityOverride(IActivityOverride i)
    {
        mActivityOverrideList.add(i);
    }

    //在Activity onPause触发的时候回调
    public static void onPause() {
        int i;
        for(i=mActivityOverrideList.size()-1;i>=0;i--)
        {
            IActivityOverride curr = (IActivityOverride)mActivityOverrideList.get(i);
            curr.onPause();
        }
    }

    //在Activity onResume触发的时候回调
    public static void onResume() {
        int i;
        for(i=mActivityOverrideList.size()-1;i>=0;i--)
        {
            IActivityOverride curr = (IActivityOverride)mActivityOverrideList.get(i);
            curr.onResume();
        }
    }

    //在Activity onDestroy触发的时候回调
    public static void onDestroy()
    {
        int i;
        for(i=mActivityOverrideList.size()-1;i>=0;i--)
        {
            IActivityOverride curr = (IActivityOverride)mActivityOverrideList.get(i);
            curr.onDestroy();
        }
    }

    //在Activity onRequestPermissionsResult触发的时候回调
    public static void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults)
    {
        QWEvent evt = new QWEvent(EVT_REQUEST_PERMISSIONS_RESULT,requestCode);
        g_Events.dispatchEvent(evt);
    }

    //在Activity onActivityResult触发的时候回调
    public static void  onActivityResult(int requestCode, int resultCode, Intent data)
    {
        HashMap<String,Object> param = new HashMap<String, Object>();
        param.put("requestCode",requestCode);
        param.put("resultCode",resultCode);
        param.put("data",data);

        QWEvent evt = new QWEvent(EVT_ACTIVITY_RESULT,param);
        g_Events.dispatchEvent(evt);
    }

    //监听事件
    public static void addEventListener(String type,ICallbackQWEvent listener)
    {
        g_Events.addEventListener(type,listener);
    }

    //移除监听
    public static void  removeEventListener(String type,ICallbackQWEvent listener)
    {
        g_Events.removeEventListener(type,listener);
    }



    public static Activity getActivity(){
        return m_BaseFuncs.getActivity();
    }

    public static void trackEvent(String evtName, final Map<String, Object> evtParams)
    {
        final String n = evtName;

        class MRunnable implements Runnable
        {
            @Override
            public void run() {
                m_BaseFuncs.trackEvent(n,evtParams);
            }

        }

        getActivity().runOnUiThread( new MRunnable() );

    }



    public static void trackEvent(String evtName)
    {
        final String n = evtName;

        class MRunnable implements Runnable
        {
            @Override
            public void run() {
                Map<String, Object> eventValue = new HashMap<>();
                m_BaseFuncs.trackEvent(n,eventValue);
            }
        }
        getActivity().runOnUiThread( new MRunnable() );
    }

    public static void vibrator(int milliseconds)
    {
        if(m_VibratorService==null) {
            Activity  mMainActivity = getActivity();
            m_VibratorService = (Vibrator) mMainActivity.getSystemService(mMainActivity.VIBRATOR_SERVICE);
        }
        m_VibratorService.vibrate(milliseconds);
    }

    public  static void setKeepScreenOn(boolean on)
    {
        if(on) {
            getActivity().getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
            );
        }else
        {
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    public static void openURL(String url)
    {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        getActivity().startActivity(intent);
    }

    //googlePlay com.android.vending
    public static String getInstallerPackageName()
    {
        Activity activity = getActivity();
        String re = activity.getPackageManager().getInstallerPackageName(activity.getPackageName());
        return (re==null)?"":re;
    }

    public static String getLang() {
        Locale locale;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            locale = getActivity().getResources().getConfiguration().getLocales().get(0);
        else
            locale = getActivity().getResources().getConfiguration().locale;

        return locale.getLanguage();
    }

    public static void QuitApp()
    {
        //Process.killProcess(android.os.process.pId());
        System.exit(0);
    }

    static Vibrator m_VibratorService;
    static IBaseFuncs m_BaseFuncs;
    static QWEventDispatcher g_Events = new QWEventDispatcher();
    static ArrayList mActivityOverrideList = new ArrayList();
}


